package cn.bob.org.controller;

import cn.bob.basic.utils.AjaxResult;
import cn.bob.basic.utils.PageList;
import cn.bob.org.domain.UserPic;
import cn.bob.org.query.UserPicQuery;
import cn.bob.org.service.UserPicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.List;

@RequestMapping("/userPic")
@RestController // Controller + responseBody 当前的controller返回的都是json
public class UserPicController {

    @Autowired
    private UserPicService userPicService;

    /*查询通过id*/
    @GetMapping("/{picId}")
    public UserPic findById(@PathVariable("picId") Long picId) {
        System.out.println(picId);
        return userPicService.findById(picId);
    }

    /*查询所有图片数据*/
    @GetMapping
    public List<UserPic> findAll(){
        return userPicService.findAll();
    }

    /*修改图片*/
    @PutMapping
    public AjaxResult update(@RequestBody UserPic userPic){
        try {
            userPicService.update(userPic);
        return AjaxResult.me().success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.me().fail();
    }

    /*删除图片*/
    @DeleteMapping("/{picId}")
    public AjaxResult delete(@PathVariable("picId") Long picId){
        try {


            UserPic userPic = userPicService.findById(picId);
            File file = new File("D:\\Test\\ProfilePhoto\\"+userPic.getUrl());
            file.delete();
            userPicService.delete(picId);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.me().fail();
    }

    /*分页查询*/
    @PostMapping
    public PageList<UserPic> queryByPage(@RequestBody UserPicQuery query){
        return userPicService.queryByPage(query);
    }


    @PatchMapping
    public AjaxResult batchDel(@RequestBody List<Long> ids){
        try {
            for (Long picId : ids) {
                System.out.println(picId);
                UserPic userPic = userPicService.findById(picId);
                File file = new File("D:\\Test\\ProfilePhoto\\"+userPic.getUrl());
                file.delete();
                userPicService.delete(picId);
            }
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.me().fail();
    }







}
